import base64
import hmac
import urllib

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

#from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from myapp.models import User
from mydjango.settings import UPLOAD_ROOT
from mydjango.settings import Base_URL_vue
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#定义host和端口
host = '127.0.0.1'
port = 6379
r = redis.Redis(host=host,port=port)

#钉钉登录回调
def Ex_ding_back(request):
    #获取授权码code&返回的state
    code = request.GET.get("code",'null')
    state = request.GET.get("state",'null')


    #钉钉开放平台提供的
    appId = 'dingoajtt4hfxbsp1tpdyv'
    appSecret = 'R7krrBZnXzoRGrHaJR9dhaYb_qgTOtq86dpreWThg60tiHfoenzCyZ6zNOmxb-9Y'
    #构建时间戳(单位毫秒)
    now_milli_time = str(int(time.time() * 1000))
    #构建签名
    signature = base64.b64encode(
        hmac.new(
            appSecret.encode('utf-8'),
            now_milli_time.encode('utf-8'),
            digestmod=hashlib.sha256
        ).digest()).decode("utf-8")
    #通过临时授权码获取用户个人信息
    #post参数需要json类型
    #url签名参数写进url，data参数使用json
    res = requests.post(url='https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey='
                            +appId+'&timestamp='+now_milli_time+'&signature='+urllib.parse.quote(signature),
        data=json.dumps({
            "tmp_auth_code": code
        }),
        headers={
            'Content-Type': 'application/json'
        }
    )

    #转码，获取用户名
    res = json.loads(res.text)
    name = res['user_info']['nick']

    # 判断是否使用过钉钉登录
    user = User.objects.filter(username=name).first()
    ding_id = ''
    user_id = ''
    if user:
        # 表示已经使用过微博登录并且成功注册到了数据库
        ding_id = user.username
        user_id = user.id
    else:
        # 首次登录，需要存储到数据库
        user = User(username=name, password='', type=0)
        user.save()

        # 查询用户ID
        user = User.objects.filter(username=name).first()
        ding_id = ding_id
        user_id = user.id

    return redirect(Base_URL_vue+'?ding_id='+str(ding_id)+'&user_id='+str(user_id))

#登录模块
class Ex_Login(APIView):
    def get(self,request):
        #接受参数
        username = request.GET.get("username",'null')
        password = request.GET.get("password",'null')

        #查询数据库
        user = User.objects.filter(username=username,password=make_password(password)).first()
        if user:
            res = {}
            res['code']=200
            res["message"]='登录成功'
            res['username'] = user.username
            res['uid'] = user.id
            return Response(res)
        else:
            res = {}
            res['code'] = 450
            res["message"] = '用户名或密码错误'
            return Response(res)


#注册模块
class Ex_Register(APIView):
    def get(self,request):
        username = request.GET.get("username","null")
        password = request.GET.get("password",'null')

        #排重
        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res["code"] = 405
            res["message"] = '该用户名已存在！'
            return Response(res)
        else:
            user = User(username=username,password=make_password(password))
            user.save()
            res = {}
            res["code"] = 200
            res["message"] = '恭喜注册成功！'
            return Response(res)

#md5加密逻辑
def make_password(mypass):

    #生成md5对象
    md5 = hashlib.md5()
    #定义机密对象——进行强转
    sign_str = str(mypass)
    #转码
    sign_utf8 = sign_str.encode(encoding="utf-8")
    #加密
    md5.update(sign_utf8)
    #生成密钥串
    md5_server = md5.hexdigest()

    return md5_server
